﻿using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using MyFloridaHouse.DataAccess.Extensions;
using MyFloridaHouse.libSvDTO;
using MyFloridaHouse.DataAccess.DTO;
using System.Linq;
using MyFloridaHouse.DataAccess.SQLServerTypes;
using MyFloridaHouse.libSvBingMapsMultiShape;

namespace MyFloridaHouse.DataAccess
{
    public partial class DAL_CensusData
    {
        public List<SQLRegionDTO> GetRegionListShapes(double zoomLevel, int iLayerID, List<int> regionIDList)
        {
            var tableNamePrefix = (from tbl in DAL_Global.TableLayers
                                   where tbl.layerid == iLayerID
                                   select tbl.prefix).Single();
            string iLayerTableName = tableNamePrefix + "Regions";

            //todo:  Aackk!  Remove this county table name kludge once shapes are in table storage by level
            if ((10 > zoomLevel) & (iLayerTableName == "tl10county10Regions"))
            {
                // substitute simplified counties to speed up user interface
                iLayerTableName = "tl10county10RegionsSmp";
            }

            List<SQLRegionDTO> itemList = new List<SQLRegionDTO>();
            string storedProcedureName = "flh_GetRegionListShapes";

            using (SqlConnection db = Connect())
            {
                string iRegionIDList = string.Join(",", regionIDList);

                SqlCommand StoredProcedureCommand = new SqlCommand(storedProcedureName, db);
                StoredProcedureCommand.CommandType = CommandType.StoredProcedure;
                SqlParameter dataPartIDParm = StoredProcedureCommand.Parameters.AddWithValue("tableName", iLayerTableName);
                dataPartIDParm.Direction = ParameterDirection.Input;
                SqlParameter dataPartIDParm2 = StoredProcedureCommand.Parameters.AddWithValue("regionIDList", iRegionIDList);
                dataPartIDParm2.Direction = ParameterDirection.Input;

                db.Open();
                using (SqlDataReader rdr = StoredProcedureCommand.ExecuteReader())
                {
                    while (rdr.Read())
                    {
                        itemList.Add(SQLRegionDTODataContract.DataContract(rdr));
                    }
                }
            }

            var x = from q in itemList
                    select q;
            List<SQLRegionDTO> regionShapeList = x.ToList();


            //TODO: When we convert to table storage of MapMultiShapes, we can pre-calculate reduced shapes per zoom level, the store serialized compressed zoom level appropriate multi map shapes to be returned directly to the client and popped into the map!

            return regionShapeList;
        }

    }
}
